#include "femainwindow_private.h"

#include <QChildEvent>
#include <QPainter>
#include <QPaintEvent>
#include <QMap>

struct FeMainWindowPrivate
{
	QMap<QWidget *, int> priority;
	QMultiMap<int, QWidget *> widgets;
};

//static void printWidgets(const QMultiMap<int, QWidget *> widgets)
//{
//	qDebug("Widget stack:");
//	QMultiMap<int, QWidget *>::const_iterator i;
//	for(i = widgets.begin(); i != widgets.end(); ++i)
//	{
//		int priority = i.key();
//		qDebug("-prio: %d", priority);
//		const QList<QWidget *> values = widgets.values(priority);
//		QWidget *w;
//		foreach(w, values)
//		{
//			qDebug(" widget: %x", w);
//		}
//	}
//
//}

// FeMainWindow
FeMainWindow::FeMainWindow(QWidget *parent)
	: QWidget(parent)
{
	setAttribute(Qt::WA_OpaquePaintEvent, true);
	setAttribute(Qt::WA_NoSystemBackground, true);

	d = new FeMainWindowPrivate;
}

FeMainWindow::~FeMainWindow()
{
	delete d;
}

int FeMainWindow::childWidgetPriority(QWidget *child) const
{
	Q_ASSERT(child->parent() == this);
	QMap<QWidget *, int>::iterator i = d->priority.find(child);
	Q_ASSERT(i != d->priority.end());
	return i.value();
}

void FeMainWindow::setChildWidgetPriority(QWidget *child, int priority)
{
	Q_ASSERT(child->parent() == this);
	QMap<QWidget *, int>::iterator i = d->priority.find(child);
	Q_ASSERT(i != d->priority.end());
	d->widgets.remove(i.value(), child);
	d->widgets.insert(priority, child);
	i.value() = priority;
	placeWidget(child, priority);
}


void FeMainWindow::paintEvent(QPaintEvent *e)
{
	QPainter p(this);
	p.fillRect(e->rect(), Qt::black);
}

void FeMainWindow::childEvent(QChildEvent *e)
{
	QWidget::childEvent(e);
	QWidget *child = qobject_cast<QWidget *>(e->child());
	if(child)
	{
		switch(e->type())
		{
		case QEvent::ChildAdded:
			{
				int priority = 0;
				// TODO detect inital priority
				d->priority.insert(child, priority);
				d->widgets.insert(priority, child);
			}
			break;

		case QEvent::ChildRemoved:
			{
				QMap<QWidget *, int>::iterator i = 
					d->priority.find(child);
				Q_ASSERT(i != d->priority.end());
				d->widgets.remove(i.value(), child);
				d->priority.remove(child);
			}
			break;
		}
	}
}

void FeMainWindow::placeWidget(QWidget *child, int priority)
{
	QMultiMap<int, QWidget *>::iterator i = d->widgets.lowerBound(priority+1);
	if(i == d->widgets.end())
	{
		child->raise();
	}
	else 
	{
		QList<QWidget *> stack = d->widgets.values(i.key());
		child->stackUnder(stack.last());
	}
}